var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var WxParse = require('../../utils/wxParse/wxParse.js');
var common = require('../../utils/common.js');
var Pagination = require('../../utils/pagination.js');
var ShareActionSheet = require('../../components/shareActionSheet/index.js');
var MPage = require('../MPage.js');
var app = getApp();
var sliderWidth = 126; // 需要设置slider的宽度，用于计算中间位置

Page(common.extendPage(MPage, {
    data: {
        dataLoaded: false,
        winHei: 0,
        swiperHei: 0,
        curSwiperIndex: 0,

        tabs: ["出刀记录", "总排行榜"],
        activeIndex: 0,
        sliderOffset: 0,
        sliderLeft: 0,
        sliderWidth,

        page1: {
            nextPageLoading: false,
            pageLoadedAll: false,
        },
        page2: {
            nextPageLoading: false,
            pageLoadedAll: false,
        },

        list: [],
        ranks: [],
        records: [],

        isShowPanel: false,
    },

    onShareAppMessage: function() {
        var {
            haggleId,
            cutId
        } = this.data;
        var {
            actInfo
        } = this.data;

        return {
            title: actInfo.title,
            path: `pages/cut/index?haggleId=${haggleId}&cutId=${cutId}`,
        }
    },

    onPullDownRefresh() {
        this._init();
    },

    onLoad: function(options) {
        var {
            haggleId,
            cutId
        } = util.parseOptions(options);

        this.setData({
            isLogin: !!app.getUserSid(),
            haggleId,
            cutId,
        });

        this._init();
    },

    onLoginSuc() {
        this.setData({
            isLogin: true
        });
    },

    _showLogin() {
        this.setData({
            isLoginShow: true
        });
    },

    _init() {
        common.initApp({
            loginSuc: () => {
                this._initTabs();
                this._fetch();
                this.$loginSuc();
                this._shareAs = new ShareActionSheet({
                    page: this,
                    scope: 'shareActionSheet'
                });
            }
        });
    },

    _showActionSheet() {
        var {
            haggleId,
            cutId,
        } = this.data;

        this._shareAs.show({
            type: 4,
            actId: haggleId,
            cutId
        });
    },

    /**
     * swiper切换时
     */
    _swiperChange: function(evt) {
        this.setData({
            curSwiperIndex: evt.detail.current,
        });
    },

    /**
     * 预览图片
     */
    _previewImg: function(evt) {
        var formId = evt.detail.formId;
        wx.previewImage({
            current: this.data.imageUrls[this.data.curSwiperIndex],
            urls: this.data.imageUrls,
        })
        common.submitForm(formId);
    },

    _initTabs() {
        var that = this;

        wx.getSystemInfo({
            success: function(res) {
                that.setData({
                    sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
                    sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
                });
            }
        });
    },

    tabClick: function(e) {
        var id = e.currentTarget.id;
        var formId = e.detail.formId;

        this.setData({
            sliderOffset: e.currentTarget.offsetLeft,
            activeIndex: id
        });
        common.submitForm(formId);
    },

    /**
     * 根据图片高度设置swiper高度
     */
    _swiperImgLoaded: function(evt) {
        if (this.data.swiperHei > 0) {
            return;
        }
        var self = this;
        var ratio = evt.detail.height / evt.detail.width;

        wx.getSystemInfo({
            success: function(res) {
                self.setData({
                    dataLoaded: true,
                    swiperHei: res.windowWidth * ratio
                });
            }
        });
    },

    /**
     * 预览图片
     */
    _previewImg: function(evt) {
        var formId = evt.detail.formId;
        wx.previewImage({
            current: this.data.imageUrls[this.data.curSwiperIndex],
            urls: this.data.imageUrls,
        })
        common.submitForm(formId);
    },

    _fetch() {
        var self = this;
        var {
            haggleId,
            cutId
        } = this.data;

        ajax.G('/openapi/CActivity/showHaggle', {
            haggle_id: haggleId,
            cut_id: cutId,
        }, function(data) {
            wx.stopPullDownRefresh();

            var result = data.result;
            var {
                cut_id: cutId,
                actInfo,
                goods,
                actGoodsInfo,
                ranks,
                records,
                joinCount,
                haggleState,
                hagglePay,
                joinHaggle,
                myHaggle,
                orderInfo,
                fromHaggleInfo: fromInfo,
                lastHaggleInfo: lastInfo,
            } = result;

            self._lastTime = actInfo['left_time'];

            if (goods.goodsDetail) {
                WxParse.wxParse('article', 'html', goods.goodsDetail, self, 0);
            }

            self.setData({
                cutId,
                bannerType: 0,
                imageUrls: goods['imageUrls'],
                goods,
                actGoodsInfo,
                actInfo,
                // ranks,
                // records,
                joinCount,
                haggleState, //砍价状态 0.未完成 1.已完成
                hagglePay, //是否可以以底价购买
                joinHaggle, //是否已砍过价
                myHaggle, //是否是发起人
                orderInfo,
                fromInfo,
                lastInfo,
            });

            self._getList(0);
            self._getList(1);

            if (self._actTimer) {
                clearTimeout(self._actTimer);
            }
            if (self._lastTime && self._lastTime > 0) {
                self._actTimerDown();
            }
        }, function() {
            wx.stopPullDownRefresh();
        });
    },

    /**
     * 砍价
     * @return {[type]} [description]
     */
    _cut(evt) {
        var self = this;
        var {
            mustStart //指定发起砍价
        } = evt.target.dataset;
        var {
            haggleId,
            cutId
        } = this.data;
        var ajaxParams = {
            haggle_id: haggleId,
        };

        if (!this.data.isLogin) {
            this._showLogin();
            return;
        }

        if (!mustStart && cutId) {
            ajaxParams.cut_id = cutId;
        }

        ajax.P('/openapi/CActivity/joinHaggle', ajaxParams, function(data) {
            var result = data.result;

            self.setData({
                cutId: result.cut_id
            });
            util.alert(result.content);
            self._fetch();
        });
    },

    /**
     * 底价购买
     * @return {[type]} [description]
     */
    _buy() {
        var self = this;
        var {
            haggleId,
            goods,
            actGoodsInfo,
            haggleState,
        } = this.data;

        if (haggleState != 1) {
            return util.alert('还没有砍到底价，赶紧邀请好友帮砍吧');
        }
        var ajaxUrl = '/openapi/CHome/showQuickBuy';
        var ajaxParams = {
            goodsId: goods.id,
            skuId: actGoodsInfo.skuId,
            act_id: haggleId,
            act_type: 2,
            amount: 1,
        };

        ajax.P(ajaxUrl, ajaxParams, function(data) {
            self._toConfirmPay();
        });
    },

    /**
     * 跳转至订单确认页
     * @return {[type]} [description]
     */
    _toConfirmPay() {
        var {
            haggleId,
            goods,
            actGoodsInfo,
        } = this.data;

        wx.navigateTo({
            url: '/pages/confirmOrder/confirmOrder?goodsId=' + goods.id + '&skuId=' + actGoodsInfo.skuId + '&amount=' + 1 + '&actId=' + haggleId + '&actType=' + 2
        })
    },

    /**
     * 倒计时
     * @return {[type]} [description]
     */
    _actTimerDown() {
        var _self = this;
        var sec = _self._lastTime;
        var lastTimeStr = util.getTimeBySec(sec, 'd');

        _self.setData({
            lastTimeStr,
        });
        if (sec == 0) {
            clearTimeout(_self._actTimer);
            _self._fetch();
            return;
        }
        _self._lastTime--;
        _self._actTimer = setTimeout(function() {
            _self._actTimerDown();
        }, 1000)
    },

    /**
     * 总排行榜；出刀记录
     * @param  {[type]} type [0.出刀记录 1.总排行榜]
     * @return {[type]}      [description]
     */
    _getList(type) {
        var _self = this;
        var {
            haggleId,
            cutId,
        } = this.data;
        var pageOrder = +type + 1;
        var url = '/openapi/CActivity/haggleRecords';
        var ajaxParams = {
            haggle_id: haggleId,
        };

        if (type == 1) {
            url = '/openapi/CActivity/haggleRanks';
        } else {
            ajaxParams.cut_id = cutId;
        }
        _self['pagination' + pageOrder] = new Pagination({
            url,
            params: ajaxParams,
            beforeGetPage(page) {
                var pageObj = _self.data['page' + pageOrder];

                if (page > 1) {
                    pageObj.nextPageLoading = true;
                    _self.setData({
                        [`page${pageOrder}`]: pageObj
                    });
                }
            },
            getPageSuccess(page, data) {
                var result = data.result;
                var pageObj = _self.data['page' + pageOrder];
                var key = type == 0 ? 'records' : 'ranks';
                var list = _self.data[key] || [];
                var curList = result[key] || [];
                var data = {};

                if (page == 1) {
                    if (pageOrder == 1) {
                        data = {
                            dataLoaded: true,
                        };
                    }
                    list = curList;
                } else {
                    list = list.concat(curList)
                }

                if (curList.length < 10) {
                    pageObj.pageLoadedAll = true;
                }

                pageObj.nextPageLoading = false;

                data['page' + pageOrder] = pageObj;
                data[key] = list;

                _self.setData(data);
            }
        });
    },

    /**
     * 加载更多
     * @return {[type]} [description]
     */
    _loadMore() {
        var _self = this;
        var num = +_self.data.activeIndex + 1;
        var pagination;

        if (_self.data['page' + num].pageLoadedAll) {
            return;
        }

        pagination = _self['pagination' + num];

        pagination && pagination.loadNext();
    },

    /**
     * 展开商品详情
     * @return {[type]} [description]
     */
    _showPanel() {
        this.setData({
            isShowPanel: !this.data.isShowPanel
        })
    },

}));